package com.lx.backstagemanagement.web;

import com.lx.backstagemanagement.common.ResultCode;
import com.lx.backstagemanagement.constant.SysKeyWord;
import com.lx.backstagemanagement.entity.User;
import com.lx.backstagemanagement.security.model.UserContext;
import com.lx.backstagemanagement.security.model.token.AccessToken;
import com.lx.backstagemanagement.security.model.token.TokenFactory;
import com.lx.backstagemanagement.service.impl.UserServiceImpl;
import com.lx.backstagemanagement.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author lee
 */
@RestController
public class HomeController {
    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private TokenFactory tokenFactory;

    @GetMapping(value = "/logout")
    public ResultCode logOut(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute(SysKeyWord.getUserName());
        return ResultCode.SUCCESS;
    }

    @PostMapping(value = "/user/login")
    public ResultCode login(User user, HttpServletResponse response, HttpServletRequest request) {
        user.setPassword(MD5Utils.md5(user.getPassword()));
        List<User> users = userServiceImpl.login(user);
        HttpSession session = request.getSession();
        if (users.size() >= 1) {
            session.setAttribute(SysKeyWord.getUserName(), users.get(0));
            return ResultCode.getSuccessReturn(users.get(0));
        } else {
            return ResultCode.getFailure(ResultCode.NOT_FOUND, "用户名或密码有错");
        }
    }

    @PostMapping("/auth/login")
    public AccessToken getToken(@RequestBody User userInfo) {
        int i=0;
        User name = userServiceImpl.login(userInfo).get(0);
//        List<GrantedAuthority> collect = userServiceImpl.getRoleByUser(userInfo.getUserName()).stream().map(e -> new SimpleGrantedAuthority(e.authority())).collect(Collectors.toList());

        AccessToken accessToken = tokenFactory.createAccessToken(UserContext.create(name.getUsername()));
        return accessToken;
    }


}
